import React, { useEffect, useContext, useMemo, useState, useCallback, useRef } from 'react';
import { Form, Divider, Pagination, message, Row, Col, Spin, Select as AntdSelect } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import { useLocation } from 'react-router-dom';
import { getInterfacesList, getWebInterface } from '../../servers/servers';

import { InterfacesInfo } from '../../schema/BasicResource';

import qs from 'query-string';
import { CustomFormItemsHoc } from './CustomFormHoc';
import { cloneDeep, debounce } from 'lodash';

/**
 * 接口组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-接口组件
 */
const InterfaceComponent: React.FC = () => {
  const [form] = useForm();
  // Table loading状态
  const [selecting, setSelecting] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数-固定
  const pageSize = 6;
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [interfacesList, setInterfacesList] = useState<InterfacesInfo[]>([]);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');
  const { versionId, selectedData, onInputChange, isView } = useContext(InspectorContext);
  const _selectedData = cloneDeep(selectedData);
  const _requestParam = _selectedData.interfaceInfo.requestParam;
  const _responseParam = _selectedData.interfaceInfo.responseParam;
  // console.log('_requestParam', _requestParam);

  const { Input, TextArea, Option } = CustomFormItemsHoc({ disabled: isView });
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);
  const robotId = Number(query.robotId);

  /**
   * Table数据加载
   */
  const initInterfaceList = useCallback(async () => {
    // setTableLoading(true);
    try {
      const res = await getInterfacesList({
        pageNo: current,
        pageSize: pageSize,
        versionId,
        interfaceName: searchText,
      });
      if (res.code === 0) {
        setInterfacesList(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('initInterfaceList -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    // setTableLoading(false);
  }, [current, searchText, versionId]);

  const getInterfaceInfo = async (interfaceId: number) => {
    setSelecting(true);
    try {
      const res = await getWebInterface({
        interfaceId,
      });
      console.log('getInterfaceInfo -> res', res);
      if (res.code === 0) {
        const {
          interfaceName = '',
          callMode = 'get',
          url = '',
          requestParams,
          responseParams,
        } = res.data;

        // [{"interfaceParam":"name","internalParam":"张三"}] => [{"key":"name","value":"张三"}]
        let requestParam: any = [];
        if (requestParams && requestParams.length) {
          requestParam = requestParams.map((item: any) => {
            return { key: item.interfaceParam, value: item.internalParam };
          });
        }
        console.log('getInterfaceInfo -> requestParam', requestParam);

        // [{"interfaceParam":"name","internalParam":"张三"}] => [{"key":"name","value":"张三"}]
        let responseParam: any = [];
        if (responseParams && responseParams.length) {
          responseParam = responseParams.map((item: any) => {
            return { key: item.interfaceParam, value: item.internalParam };
          });
        }
        console.log('getInterfaceInfo -> responseParam', responseParam);

        const interfaceInfo = {
          interfaceId: interfaceId,
          name: interfaceName,
          method: callMode,
          /**接口地址 */
          url: url,
          requestParam: requestParam,
          // requestParam: [],
          responseParam: responseParam,
        };
        console.log('getInterfaceInfo -> interfaceInfo', interfaceInfo);

        onInputChange('interfaceInfo', interfaceInfo, true);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSelecting(false);
  };

  // 数据初始化 && 数据更新
  useEffect(() => {
    initInterfaceList();
  }, [initInterfaceList]);

  useEffect(() => {
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    form.setFieldsValue(selectedData);
    form.validateFields();
  }, [form, selectedData]);

  return (
    <>
      <Spin spinning={selecting}>
        <Form layout="vertical" form={form}>
          <Form.Item
            label="接口组件名称"
            name="title"
            rules={[
              {
                required: true,
                whitespace: true,
                max: 10,
                message: '仅支持输入10个以内字符',
              },
            ]}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input
              maxLength={10}
              // onChange={e => {
              //   onInputChange("title", e.target.value, e.type === "blur");
              // }}
              onBlur={(e: { target: { value: any }; type: string }) => {
                onInputChange('title', e.target.value, e.type === 'blur');
              }}
            />
          </Form.Item>
          <Form.Item label="调用接口" required>
            <AntdSelect
              disabled={isView}
              showSearch
              placeholder="请选择接口"
              value={selectedData.interfaceInfo.name}
              getPopupContainer={(triggerNode: { parentElement: any }) => triggerNode.parentElement}
              onSearch={debounce(text => {
                setCurrent(1);
                setSearchText(text.trim());
              }, 700)}
              filterOption={false}
              onChange={(key: number) => {
                console.log('InterfaceComponent:React.FC -> key', key);
                getInterfaceInfo(key);
              }}
              /**自定义下拉区域 */
              dropdownRender={(menu: any) => (
                <div>
                  {menu}
                  {total > 0 && (
                    <>
                      <Divider style={{ margin: '4px 0' }} />
                      <div style={{ padding: '8px', textAlign: 'center' }}>
                        <Pagination
                          simple
                          current={current}
                          total={total}
                          onChange={current => {
                            setCurrent(current);
                          }}
                        />
                      </div>
                    </>
                  )}
                </div>
              )}
            >
              {/* 接口列表 */}
              {interfacesList.map(item => {
                return (
                  <Option key={item.interfaceId} value={item.interfaceId}>
                    {item.interfaceName}
                  </Option>
                );
              })}
            </AntdSelect>
          </Form.Item>
          {!selectedData.interfaceInfo.name && (
            <Form.Item>
              <a
                href={`/webapp/outbound/ai/robots/version/flow?robotId=${robotId}&type=basicResource`}
                target="blank"
              >
                添加更多接口
              </a>
            </Form.Item>
          )}
          {selectedData.interfaceInfo.name && (
            <>
              <Divider plain orientation="center">
                接口信息
              </Divider>
              <div className="label-wrap">
                <label>请求方式:</label>
                {selectedData.interfaceInfo.method}
              </div>
              <div className="label-wrap">
                <label>接口地址:</label>
                {selectedData.interfaceInfo.url}
              </div>
              <Divider plain orientation="center">
                请求参数
              </Divider>
              {_requestParam && _requestParam.length > 0 && (
                <>
                  <Row gutter={[0, 4]}>
                    <Col span={12}>
                      <label>请求参数</label>
                    </Col>
                    <Col span={12}>
                      <label>内部参数</label>
                    </Col>
                  </Row>
                  {_requestParam.map((item: any, index: number) => {
                    return (
                      <Row gutter={[0, 4]} key={index}>
                        <Col span={12} style={{ lineHeight: '30px' }}>
                          {item.key}
                        </Col>
                        <Col span={12}>
                          <TextArea
                            defaultValue={item.value}
                            onChange={debounce(e => {
                              const val = e.target.value;
                              const type = e.type;
                              const _interfaceInfo = _selectedData.interfaceInfo;
                              _interfaceInfo['requestParam'][index]['value'] = val;
                              // onInputChange('interfaceInfo', _interfaceInfo, e.type === 'blur');
                              onInputChange('interfaceInfo', _interfaceInfo, true);
                            }, 500)}
                            onBlur={(e: any) => {
                              const val = e.target.value;
                              const type = e.type;
                              const _interfaceInfo = _selectedData.interfaceInfo;
                              _interfaceInfo['requestParam'][index]['value'] = val;
                              onInputChange('interfaceInfo', _interfaceInfo, true);
                              // onInputChange('interfaceInfo', _interfaceInfo, e.type === 'blur');
                            }}
                            // value={item.value}
                            // onChange={(e: { target: { value: any }; type: string }) => {
                            //   const val = e.target.value;
                            //   const interfaceInfo = cloneDeep(selectedData.interfaceInfo);
                            //   interfaceInfo['requestParam'][index]['value'] = val;
                            //   onInputChange('interfaceInfo', interfaceInfo, e.type === 'blur');
                            // }}
                            // onBlur={(e: { target: { value: any }; type: string }) => {
                            //   const val = e.target.value;
                            //   const interfaceInfo = cloneDeep(selectedData.interfaceInfo);
                            //   interfaceInfo['requestParam'][index]['value'] = val;
                            //   onInputChange('interfaceInfo', interfaceInfo, e.type === 'blur');
                            // }}
                          />
                        </Col>
                      </Row>
                    );
                  })}
                </>
              )}
              <Divider plain orientation="center">
                返回参数
              </Divider>
              {_responseParam && _responseParam.length > 0 && (
                <>
                  <Row gutter={[0, 4]}>
                    <Col span={12}>
                      <label>返回参数</label>
                    </Col>
                    <Col span={12}>
                      <label>内部参数</label>
                    </Col>
                  </Row>
                  {_responseParam.map((item: any, index: number) => {
                    return (
                      <Row gutter={[0, 4]} key={index}>
                        <Col span={12}>{item.key}</Col>
                        <Col span={12}>
                          <TextArea
                            defaultValue={item.value}
                            onChange={debounce(e => {
                              const val = e.target.value;
                              const type = e.type;
                              const _interfaceInfo = _selectedData.interfaceInfo;
                              _interfaceInfo['responseParam'][index]['value'] = val;
                              // onInputChange('interfaceInfo', _interfaceInfo, e.type === 'blur');
                              onInputChange('interfaceInfo', _interfaceInfo, true);
                            }, 500)}
                            onBlur={(e: any) => {
                              const val = e.target.value;
                              const type = e.type;
                              const _interfaceInfo = _selectedData.interfaceInfo;
                              _interfaceInfo['responseParam'][index]['value'] = val;
                              onInputChange('interfaceInfo', _interfaceInfo, true);
                              // onInputChange('interfaceInfo', _interfaceInfo, e.type === 'blur');
                            }}
                            // value={item.value}
                            // onChange={(e: { target: { value: any }; type: string }) => {
                            //   const interfaceInfo = cloneDeep(selectedData.interfaceInfo);
                            //   interfaceInfo['responseParam'][index]['value'] = e.target.value;
                            //   onInputChange('interfaceInfo', interfaceInfo, e.type === 'blur');
                            // }}
                            // onBlur={(e: { target: { value: any }; type: string }) => {
                            //   const interfaceInfo = cloneDeep(selectedData.interfaceInfo);
                            //   interfaceInfo['responseParam'][index]['value'] = e.target.value;
                            //   onInputChange('interfaceInfo', interfaceInfo, e.type === 'blur');
                            // }}
                          />
                        </Col>
                      </Row>
                    );
                  })}
                </>
              )}
            </>
          )}
        </Form>
      </Spin>
    </>
  );
};

export default InterfaceComponent;
